package cn.springmvc.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.springmvc.model.ResultBaseBean;
import cn.springmvc.model.entity.UserBean;
import cn.springmvc.service.IFileUploadService;

@Service
public class FileUploadServiceImpl implements IFileUploadService {
	private static final Logger logger = Logger.getLogger(FileUploadServiceImpl.class);
	ResultBaseBean<String> resultBaseBean;


	public ResultBaseBean<String> fileUpload(MultipartFile file,UserBean userBean,String imageRoot) {
		resultBaseBean = new ResultBaseBean<String>();
		
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				
				String imagePath = this.createImagePath(userBean.getUserId());
				logger.info("imagePath: " + imagePath);
				
				
				String originalFileName = file.getOriginalFilename();						
				Random r = new Random();
				String finalFileName;
				int randomFileName = r.nextInt(10);
			    if(originalFileName != null){
			    	finalFileName = randomFileName + originalFileName.substring(originalFileName.lastIndexOf("."));
			    }else{
			    	finalFileName = randomFileName + ".jpg";
			    }
			    
			    File imageFile = new File(imageRoot + imagePath + finalFileName);
				if(!imageFile.exists()){
					imageFile.getParentFile().mkdirs();  
					imageFile.createNewFile(); 
					logger.info("目录" + imageRoot + imagePath + "不存在，已经创建");
				}
			     
				// 文件保存路径
				//String filePath = imageRoot + imagePath + finalFileName;
				// 转存文件
				file.transferTo(imageFile);
				
				resultBaseBean.setSuccess(true);
				resultBaseBean.setMessage("上传文件成功");
				
				ArrayList<String> list = new ArrayList<String>();
				list.add(imagePath + finalFileName);
				resultBaseBean.setResultList(list);
				
			} catch (Exception e) {
				resultBaseBean.setSuccess(false);
				resultBaseBean.setMessage("上传文件失败");
				e.printStackTrace();
				
			}
		}else{
			resultBaseBean.setSuccess(false);
			resultBaseBean.setMessage("上传文件为空");
		}
		return resultBaseBean;
	}

	private String createImagePath(Integer userId){
		StringBuffer imagePath = new StringBuffer();

		Calendar cal = Calendar.getInstance();
	    int year = cal.get(Calendar.YEAR);//获取年份
	    int month=cal.get(Calendar.MONTH)+1;//获取月份
	    int day=cal.get(Calendar.DATE);//获取日
	    	    
		imagePath.append("/");
		imagePath.append(userId);
		imagePath.append("/");
		imagePath.append(year);
		imagePath.append("/");
		imagePath.append(month);
		imagePath.append("/");
		imagePath.append(day);
		imagePath.append("/");
		
		return imagePath.toString();
	}

}
